<template>
  <a-modal
    :title="modalTitle"
    :width="500"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="6">
          <a-col >
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input @keyup.enter.native="handleSubmit" placeholder="请输入文件名称" v-decorator="['fileName', {rules: [{required: true, min: 1, message: '请输入至少一个字符的规则！'}]}]" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import {
    createFile
} from '@/api/site/template'
export default {
  data () {
    return {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 10
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 13
        }
      },
      modalTitle: '',
      modalOpera: 0, // 0：新增 1：编辑
      visible: false,
      confirmLoading: false,
      fileItem: null,
      type: null,
      form: this.$form.createForm(this)
    }
  },
  created () {
        const _this = this
        document.onkeydown = function (e) { // 按下回车提交
            const key = window.event.keyCode
            if (key === 13 && _this.visible) {
                _this.handleSubmit()
            }
        }
  },
  methods: {
    createFile (fileItem, type) {
	  this.fileItem = fileItem
    this.type = type
    this.modal('新建文件', 0)
    },
    modal (title, opera) {
      this.modalTitle = title
      this.modalOpera = opera
      this.visible = true
      this.form.resetFields()
    },
    handleSubmit () {
      const {
        form: {
          validateFields
        }
      } = this
      validateFields((errors, values) => {
        if (!errors) {
          if (this.modalOpera === 0) {
            values.type = this.type
            values.path = this.fileItem.path
            createFile(values).then(response => {
              if (response.code === 0) {
                this.$message.info(response.msg)
                this.$emit('ok')
                this.handleCancel()
              } else {
                this.$message.error(response.msg)
              }
            })
          }
        }
        this.confirmLoading = false
      })
    },
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
    }
  }
}
</script>
